package com.bckj.fastboot.core.rpc.feign.configuration;

import com.bckj.fastboot.core.rpc.feign.ExceptionErrorDecoder;
import com.bckj.fastboot.core.rpc.feign.FastSentinelFeign;
import com.bckj.fastboot.core.rpc.feign.WebExceptionInterceptor;
import feign.Feign;
import feign.RequestInterceptor;
import feign.codec.ErrorDecoder;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Scope;

@AutoConfiguration
public class FastFeignAutoConfiguration {
    public FastFeignAutoConfiguration() {
    }

    @Bean
    public RequestInterceptor headerInterceptor() {
        return (requestTemplate) -> requestTemplate.header("xyz", "feign");
    }

    @Bean
    @ConditionalOnMissingBean({ErrorDecoder.class})
    public ExceptionErrorDecoder exceptionErrorDecoder() {
        return new ExceptionErrorDecoder();
    }

    @Bean
    @ConditionalOnMissingBean
    public WebExceptionInterceptor webExceptionInterceptor() {
        return new WebExceptionInterceptor();
    }

    /**
     * 兼容alibaba feign sentinel
     */
    @Bean
    @Scope("prototype")
    @ConditionalOnMissingBean
    @ConditionalOnProperty(
            name = {"feign.sentinel.enabled"}
    )
    public Feign.Builder feignSentinelBuilder() {
        return FastSentinelFeign.builder();
    }
}
